import {app, BrowserWindow, shell, ipcMain, Menu, Tray, nativeImage, ipcRenderer} from 'electron'
import {createRequire} from 'node:module'
import {fileURLToPath} from 'node:url'
import path from 'node:path'
import os from 'node:os'
import mainIpcApi from "../api/mainIpcApi";

const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))

process.env.APP_ROOT = path.join(__dirname, '../..')

export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')
export const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
    ? path.join(process.env.APP_ROOT, 'public')
    : RENDERER_DIST

// Disable GPU Acceleration for Windows 7
if (os.release().startsWith('6.1')) app.disableHardwareAcceleration()

// Set application name for Windows 10+ notifications
if (process.platform === 'win32') app.setAppUserModelId(app.getName())

if (!app.requestSingleInstanceLock()) {
    app.quit()
    process.exit(0)
}

let mainWindow: BrowserWindow | null = null
let commandWindow: BrowserWindow | null = null
const preload = path.join(__dirname, '../preload/index.mjs')
const indexHtml = path.join(RENDERER_DIST, 'index.html')

async function createMainWindow() {
    let mainWindow = new BrowserWindow({
        title: 'boss简历投递',
        width: 1488,
        height: 950,
        icon: path.join(process.env.VITE_PUBLIC, 'favicon.ico'),
        webPreferences: {
            preload,
            contextIsolation: true,
            webSecurity: false,
        },
    });

    const loginUrl = 'https://www.zhipin.com/web/user/?ka=header-login';
    const jobRecommendUrl = 'https://www.zhipin.com/web/geek/job-recommend';

    mainWindow.webContents.on('did-finish-load', () => {
        mainWindow?.webContents.send('main-process-message', new Date().toLocaleString());
    });

    mainWindow.webContents.setWindowOpenHandler(({url}) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return {action: 'deny'};
    });

    mainWindow.webContents.on('did-fail-load', async (event, errorCode, errorDescription, validatedURL) => {
        if (validatedURL === loginUrl && errorCode === -101) { // ERR_CONNECTION_RESET
            try {
                await mainWindow.loadURL(jobRecommendUrl);
            } catch (error) {
                console.error('Failed to load job recommendation URL:', error);
            }
        }
    });

    try {
        await mainWindow.loadURL(loginUrl);
    } catch (error) {
        console.error('Failed to load login URL:', error);
    }
    mainWindow.on('close', async (e) => {
        console.log('======================Main window was closed=====================');
        e.preventDefault();

        // 调用预加载的 API 执行特定操作
        if (mainWindow.webContents && mainWindow.webContents.executeJavaScript) {
            try {
                await mainWindow.webContents.executeJavaScript(`
                window.bossHandleApi.allDataInvalid(null);
                console.log('执行了销毁操作');
            `);
            } catch (error) {
                console.error('Error executing JavaScript:', error);
            }
        } else {
            console.error('Unable to execute JavaScript in mainWindow');
        }

        console.log('-----==============----');
        // 延迟10秒后销毁窗口
        setTimeout(() => {
            mainWindow.destroy();
        }, 10000); // 10000毫秒 = 10秒
    });



    return mainWindow;
}


async function createCommandWindow() {
    commandWindow = new BrowserWindow({
        title: '控制窗口',
        width: 1488,
        height: 950,
        minWidth: 380,
        minHeight: 80,
        icon: path.join(process.env.VITE_PUBLIC, 'favicon.ico'),
        maximizable: false ,// 禁用最大化按钮
        // frame: false, // 无框窗口
        webPreferences: {
            preload,
            webSecurity: false, // 禁用同源策略和CORS
            contextIsolation: true,
        },
    })
    console.log('这个路径',path.join(process.env.VITE_PUBLIC, 'favicon.ico'))
    if (VITE_DEV_SERVER_URL) { // #298
        await commandWindow.loadURL(VITE_DEV_SERVER_URL)
        // 开发者工具关掉
        // win.webContents.openDevTools()
    } else {
        await commandWindow.loadFile(indexHtml)
    }

    // Test actively push message to the Electron-Renderer
    commandWindow.webContents.on('did-finish-load', async () => {
        commandWindow?.webContents.send('main-process-message', new Date().toLocaleString())
    })

    // Make all links open with the browser, not with the application
    commandWindow.webContents.setWindowOpenHandler(({url}) => {
        if (url.startsWith('https:')) shell.openExternal(url)
        return {action: 'deny'}
    })

    const icon = nativeImage.createFromPath('public/favicon.png');
    let tray = new Tray(icon);
    const contextMenu = Menu.buildFromTemplate([
        {label: '退出任务', type: 'radio'},
    ]);
    tray.setContextMenu(contextMenu);

    tray.setToolTip('BOSS直聘海投工具');
    tray.setTitle('BOSS直聘海投工具');
    //上面的菜单
    // Menu.setApplicationMenu(null);
}

app.whenReady().then(async () => {
    await createCommandWindow();
    //注册数据库操作
    mainIpcApi.registerDbOption()
    mainIpcApi.registerLifeCycleOption()
});


app.on('window-all-closed', () => {
    mainWindow = null
    commandWindow = null
    if (process.platform !== 'darwin') app.quit()
})

app.on('second-instance', () => {
    if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        mainWindow.focus()
    }
})

app.on('activate', () => {
    const allWindows = BrowserWindow.getAllWindows()
    if (allWindows.length) {
        allWindows[0].focus()
    } else {
        // createMainWindow()
        createCommandWindow()
    }
})

ipcMain.handle('open-win', (_, arg) => {
    const childWindow = new BrowserWindow({
        webPreferences: {
            preload,
            nodeIntegration: true,
            contextIsolation: true,
        },
    })

    if (VITE_DEV_SERVER_URL) {
        childWindow.loadURL(`${VITE_DEV_SERVER_URL}#${arg}`)
    } else {
        childWindow.loadFile(indexHtml, {hash: arg})
    }
})

// 投递窗口
let deliveryWindow: BrowserWindow | null = null
ipcMain.on('simulated-delivery', async (event, jsonPositionCondition) => {
    app.whenReady().then(async () => {
        // 创建主窗口

        try {
            // 如果存在已有的窗口，则先销毁它
            if (deliveryWindow && !deliveryWindow.isDestroyed()) {
                deliveryWindow.destroy();
            }
            deliveryWindow = await createMainWindow();
        } catch (error) {
            console.error('Error creating main window:', error);
            return;
        }

        const checkLoginInterval = setInterval(async () => {
            try {
                const url = deliveryWindow.webContents.getURL();
                if (url === 'https://www.zhipin.com/web/user/?ka=header-login') {
                    console.log('还在准备登录中');
                    return;
                }
                console.log('登录成功');
                // 如果当前 URL 不是推荐页面，跳转到推荐页面
                if (url !== 'https://www.zhipin.com/web/geek/job-recommend') {
                    try {
                        await deliveryWindow.loadURL('https://www.zhipin.com/web/geek/job-recommend');
                        console.log('跳转到推荐页面');
                    } catch (error) {
                        console.error('Error loading job recommend page:', error);
                        return;
                    }
                }
                clearInterval(checkLoginInterval);

                // Add proper delay using promises
                await new Promise(resolve => setTimeout(resolve, 5000));

                try {
                    await selectCondition(deliveryWindow, jsonPositionCondition);
                } catch (error) {
                    console.error('Error selecting condition:', error);
                    return;
                }

                await new Promise(resolve => setTimeout(resolve, 5000));

                try {
                    await selectCardCondition(deliveryWindow, jsonPositionCondition);
                } catch (error) {
                    console.error('Error selecting card condition:', error);
                    return;
                }
            } catch (error) {
                console.error('Error in checkLoginInterval:', error);
                clearInterval(checkLoginInterval);
            }
        }, 1000);
    }).catch(error => {
        console.error('Error in app.whenReady:', error);
    });

    app.on('activate', async () => {
        try {
            await createMainWindow();
        } catch (error) {
            console.error('Error creating main window on activate:', error);
        }
    });
});

// ai接口
ipcMain.on('ai-simulated-delivery',async (event,jsonPositionCondition)=>{
    app.whenReady().then(async () => {
        // 创建主窗口
        try {
            // 如果存在已有的窗口，则先销毁它
            if (deliveryWindow && !deliveryWindow.isDestroyed()) {
                deliveryWindow.destroy();
            }
            deliveryWindow = await createMainWindow();
        } catch (error) {
            console.error('Error creating main window:', error);
            return;
        }

        const checkLoginInterval = setInterval(async () => {
            try {
                const url = deliveryWindow.webContents.getURL();
                if (url === 'https://www.zhipin.com/web/user/?ka=header-login') {
                    console.log('还在准备登录中');
                    return;
                }
                console.log('登录成功');
                // 如果当前 URL 不是推荐页面，跳转到推荐页面
                if (url !== 'https://www.zhipin.com/web/geek/job-recommend') {
                    try {
                        await deliveryWindow.loadURL('https://www.zhipin.com/web/geek/job-recommend');
                        console.log('跳转到推荐页面');
                    } catch (error) {
                        console.error('Error loading job recommend page:', error);
                        return;
                    }
                }
                clearInterval(checkLoginInterval);

                // Add proper delay using promises
                await new Promise(resolve => setTimeout(resolve, 5000));

                try {
                    await selectCondition(deliveryWindow, jsonPositionCondition);
                } catch (error) {
                    console.error('Error selecting condition:', error);
                    return;
                }

                await new Promise(resolve => setTimeout(resolve, 5000));

                try {
                    await aiSelectCardCondition(deliveryWindow, jsonPositionCondition);
                } catch (error) {
                    console.error('Error selecting card condition:', error);
                    return;
                }
            } catch (error) {
                console.error('Error in checkLoginInterval:', error);
                clearInterval(checkLoginInterval);
            }
        }, 1000);
    }).catch(error => {
        console.error('Error in app.whenReady:', error);
    });


    app.on('activate', async () => {
        try {
            await createMainWindow();
        } catch (error) {
            console.error('Error creating main window on activate:', error);
        }
    });
})


//结束脚本
ipcMain.handle('stop-script', async (event, args) => {
    if (deliveryWindow.webContents && deliveryWindow.webContents.executeJavaScript) {
        try {
            await deliveryWindow.webContents.executeJavaScript(`
                window.bossHandleApi.allDataInvalid(null);
                console.log('执行了销毁操作');
            `);
        } catch (error) {
            console.error('Error executing JavaScript:', error);
        }
    } else {
        console.error('Unable to execute JavaScript in mainWindow');
    }

    console.log('-----==============----');
    // 延迟10秒后销毁窗口
    setTimeout(() => {
        deliveryWindow.destroy();
        if (deliveryWindow != null){
            deliveryWindow = null
        }
        return true
    }, 10000); // 10000毫秒 = 10秒
});

// SQLite数据库操作
//筛选 条件
async function selectCondition(mainWindow, jsonPositionCondition) {

    // 登录之后跳转到推荐页面去检查筛选条件
    const modifiedJsonPositionCondition = JSON.parse(jsonPositionCondition);

    // 获取页面中的城市值
    let cityInPage = null;
    try {
        const citySpan = await mainWindow.webContents.executeJavaScript(`
                        new Promise((resolve, reject) => {
                            const checkExist = setInterval(() => {
                                const cityElement = document.querySelector('.city-label');
                                if (cityElement) {
                                    clearInterval(checkExist);
                                    const cityLabelText = cityElement.innerText.trim();
                                    const cityLabelBeforeContent = window.getComputedStyle(cityElement, '::before').content;
                                    resolve({ text: cityLabelText, beforeContent: cityLabelBeforeContent });
                                }
                            }, 1000);
                            setTimeout(() => {
                                clearInterval(checkExist);
                                resolve(null); // 未找到元素时 resolve 为 null
                            }, 10000); // 超时时间 10秒
                        });
                    `);
        if (citySpan) {
            cityInPage = citySpan.text;
            const cityBeforeContent = citySpan.beforeContent;
            console.log(Buffer.from('log this city', 'utf-8').toString(), cityInPage);
            console.log(Buffer.from('log this ::before content', 'utf-8').toString(), cityBeforeContent);
            console.log(cityInPage == modifiedJsonPositionCondition.city);

            // 判断地区
            if (!(cityInPage == modifiedJsonPositionCondition.city)) {
                // 如果不是的话进行筛选
            }
        }
    } catch (error) {
        console.error('Error fetching city value:', error);
    }

    // 求职类型
    console.log(modifiedJsonPositionCondition.jobType);
    const jobTypeMap = {
        "不限": "sel-job-rec-jobType-0",
        "全职": "sel-job-rec-jobType-1901",
        "兼职": "sel-job-rec-jobType-1903"
    };

    const jobTypeSelector = jobTypeMap[modifiedJsonPositionCondition.jobType];
    if (jobTypeSelector) {
        await mainWindow.webContents.executeJavaScript(`
                        document.querySelector('.filter-select-dropdown').style.display = 'block';
                        const jobTypeElement = document.querySelector('li[ka="${jobTypeSelector}"]');
                        if (jobTypeElement) {
                            jobTypeElement.click();
                            console.log('Selected job type:', jobTypeElement.innerText);
                        } else {
                            console.error('Job type element not found');
                        }
                        document.querySelector('.filter-select-dropdown').style.display = 'none';
                    `);
    } else {
        console.error('Invalid job type:', modifiedJsonPositionCondition.jobType);
    }

    // 工资范围
    console.log(modifiedJsonPositionCondition.salary);
    const salaryMap = {
        "不限": "sel-job-rec-salary-0",
        "3k以下": "sel-job-rec-salary-402",
        "3-5k": "sel-job-rec-salary-403",
        "5-10k": "sel-job-rec-salary-404",
        "10-20k": "sel-job-rec-salary-405",
        "20-50k": "sel-job-rec-salary-406",
        "50k以上": "sel-job-rec-salary-407"
    };

    const salarySelector = salaryMap[modifiedJsonPositionCondition.salary];
    if (salarySelector) {
        await mainWindow.webContents.executeJavaScript(`
                        document.querySelector('.filter-select-dropdown').style.display = 'block';
                        const salaryElement = document.querySelector('li[ka="${salarySelector}"]');
                        if (salaryElement) {
                            salaryElement.click();
                            console.log('Selected salary:', salaryElement.innerText);
                        } else {
                            console.error('Salary element not found');
                        }
                        document.querySelector('.filter-select-dropdown').style.display = 'none';
                    `);
    } else {
        console.error('Invalid salary:', modifiedJsonPositionCondition.salary);
    }

    // 工作经验
    console.log(modifiedJsonPositionCondition.jobYear);
    const jobYearMap = {
        "不限": "sel-job-rec-exp-0",
        "在校生": "sel-job-rec-exp-108",
        "应届生": "sel-job-rec-exp-102",
        "经验不限": "sel-job-rec-exp-101",
        "1年以内": "sel-job-rec-exp-103",
        "1-3年": "sel-job-rec-exp-104",
        "3-5年": "sel-job-rec-exp-105",
        "5-10年": "sel-job-rec-exp-106",
        "10年以上": "sel-job-rec-exp-107"
    };

    const jobYearSelector = jobYearMap[modifiedJsonPositionCondition.jobYear];
    if (jobYearSelector) {
        await mainWindow.webContents.executeJavaScript(`
                        document.querySelector('.condition-filter-select').style.display = 'block';
                        const jobYearElement = document.querySelector('li[ka="${jobYearSelector}"]');
                        if (jobYearElement) {
                            jobYearElement.click();
                            console.log('Selected job year:', jobYearElement.innerText);
                        } else {
                            console.error('Job year element not found');
                        }
                        document.querySelector('.condition-filter-select').style.display = 'none';
                    `);
    } else {
        console.error('Invalid job year:', modifiedJsonPositionCondition.jobYear);
    }

    // 学历要求
    console.log(modifiedJsonPositionCondition.educational);
    const educationMap = {
        "不限": "sel-job-rec-degree-0",
        "初中及以下": "sel-job-rec-degree-209",
        "中专/中技": "sel-job-rec-degree-208",
        "高中": "sel-job-rec-degree-206",
        "大专": "sel-job-rec-degree-202",
        "本科": "sel-job-rec-degree-203",
        "硕士": "sel-job-rec-degree-204",
        "博士": "sel-job-rec-degree-205"
    };

    const educationSelector = educationMap[modifiedJsonPositionCondition.educational];
    if (educationSelector) {
        await mainWindow.webContents.executeJavaScript(`
                        document.querySelector('.filter-select-dropdown').style.display = 'block';
                        const educationElement = document.querySelector('li[ka="${educationSelector}"]');
                        if (educationElement) {
                            educationElement.click();
                            console.log('Selected education:', educationElement.innerText);
                        } else {
                            console.error('Education element not found');
                        }
                        document.querySelector('.filter-select-dropdown').style.display = 'none';
                    `);
    } else {
        console.error('Invalid education:', modifiedJsonPositionCondition.educational);
    }

    // 公司规模
    console.log(modifiedJsonPositionCondition.companyScale);
    const companyScaleMap = {
        "不限": "sel-job-rec-scale-0",
        "0-20人": "sel-job-rec-scale-301",
        "20-99人": "sel-job-rec-scale-302",
        "100-499人": "sel-job-rec-scale-303",
        "500-999人": "sel-job-rec-scale-304",
        "1000-9999人": "sel-job-rec-scale-305",
        "10000人以上": "sel-job-rec-scale-306"
    };

    const companyScaleSelector = companyScaleMap[modifiedJsonPositionCondition.companyScale];
    if (companyScaleSelector) {
        await mainWindow.webContents.executeJavaScript(`
                        document.querySelector('.filter-select-dropdown').style.display = 'block';
                        const companyScaleElement = document.querySelector('li[ka="${companyScaleSelector}"]');
                        if (companyScaleElement) {
                            companyScaleElement.click();
                            console.log('Selected company scale:', companyScaleElement.innerText);
                        } else {
                            console.error('Company scale element not found');
                        }
                        document.querySelector('.filter-select-dropdown').style.display = 'none';
                    `);
    } else {
        console.error('Invalid company scale:', modifiedJsonPositionCondition.companyScale);
    }

    // 模糊匹配职位名称
    console.log('likeJob=======' + modifiedJsonPositionCondition.likeJob);

    await mainWindow.webContents.executeJavaScript(`
        const jobButtons = document.querySelectorAll('.recommend-job-btn .text-content');
        let matchedJob = null;
        const likeJob = \`${modifiedJsonPositionCondition.likeJob}\`; // 使用模板字符串嵌入变量
        const regex = new RegExp(likeJob, 'i'); // 'i' 忽略大小写
    
        jobButtons.forEach(job => {
            if (regex.test(job.innerText)) {
                matchedJob = job;
                console.log('Matched job:', job.innerText); // 打印匹配到的职位信息
            }
        });
    
        if (matchedJob) {
            matchedJob.parentElement.click();
            console.log('Selected job:', matchedJob.innerText);
        } else {
            const recommendJobButton = document.querySelector('.recommend-job-btn.active');
            if (recommendJobButton) {
                recommendJobButton.click();
                console.log('No job matched the provided keyword. Defaulting to recommended job.',recommendJobButton);
            } else {
                console.error('No recommended job button found');
            }
        }
    `);


    // 需要一个 json 文件去判断用户的需求
    // 判断
    // 然后进行数据分析
    // 符合条件的就进行简历投递
    await new Promise(resolve => setTimeout(resolve, 7000)); // 等待7秒钟
}



// 投递脚本 -- 原始 备用
// async function selectCardCondition(mainWindow, jsonPositionCondition) {
//     console.log('======================================================');
//     console.log('======= 提交简历 =======');
//     console.log('======= 进入提交 =======');
//
//     const modifiedJsonPositionCondition = JSON.parse(jsonPositionCondition);
//
//
//     const jobKeywords = modifiedJsonPositionCondition.jobKeywords.length > 0
//         ? modifiedJsonPositionCondition.jobKeywords
//         : [modifiedJsonPositionCondition.likeJob];
//     console.log('职位关键词', jobKeywords);
//
//     try {
//         await mainWindow.webContents.executeJavaScript(`
//     (async () => {
//         console.log('=== 执行注入脚本 ===');
//         const modifiedJsonPositionCondition = ${JSON.stringify(modifiedJsonPositionCondition)};
//         const jobKeywords = ${JSON.stringify(jobKeywords)};
//
//         const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
//
//         const waitForElement = async (selector, timeout = 10000) => { // 延长等待时间到10秒
//             const startTime = Date.now();
//             while (Date.now() - startTime < timeout) {
//                 const element = document.querySelector(selector);
//                 if (element) {
//                     return element;
//                 }
//                 await delay(100); // 每次等待 100ms
//             }
//             console.log('等待超时，未找到元素:', selector);
//             return null;
//         };
//
//         const processJobItems = async () => {
//             const jobListItems = document.querySelectorAll('.rec-job-list .company-location');
//             console.log('找到的职位列表项:', jobListItems.length);
//
//             // 获取城市信息
//             const cities = modifiedJsonPositionCondition.city.split('/');
//
//             for (const [index, item] of jobListItems.entries()) {
//                 const location = item.innerText.trim();
//                 console.log('职位地点:', location);
//
//                 // 检查地址是否与城市模糊匹配
//                 const cityMatch = cities.some(city => location.includes(city));
//                 console.log('城市列表:', cities);
//                 console.log('城市匹配结果:', cityMatch);
//
//                 // 检查关键词是否与职位标题匹配
//                 const jobButton = item.closest('.job-card-box').querySelector('.job-name');
//                 const jobTitle = jobButton ? jobButton.innerText.trim() : ''; // 去除前后的空格
//                 console.log('职位标题:', jobTitle);
//
//                 const keywordMatch = jobKeywords.some(keyword => new RegExp(keyword, 'i').test(jobTitle)); // 忽略大小写
//                 console.log('关键词列表:', jobKeywords);
//                 console.log('关键词匹配结果:', keywordMatch);
//
//                 // 公司名字
//                 const jobName = item.closest('.job-card-box').querySelector('.boss-name');
//                 const jobNameTrim = jobName ? jobName.innerText.trim() : ''; // 去除前后的空格
//                 console.log('公司名字:', jobNameTrim);
//                 let jobDetail = ''
//                 // 输出匹配结果
//                 if (cityMatch && keywordMatch) {
//                     console.log('============职位描述匹配开始=============');
//                     const jobDescElement = await waitForElement('.job-detail-body .desc');
//                     let jobDesc = '';
//                     if (jobDescElement) {
//                         jobDesc = jobDescElement.innerText.replace(/\\n/g, '');
//                         console.log('职位描述:', jobDesc);
//                     }
//
//                     console.log('匹配上的：', '工作内容：', jobTitle, '工作地点：', location, '职位描述：', jobDesc);
//                     jobDetail = jobDesc
//                     // 模拟点击 job-card-box
//                     const jobCardBox = item.closest('.job-card-box');
//                     if (jobCardBox) {
//                         jobCardBox.click();
//                         console.log('点击了职位卡片.');
//
//                         // 轮询机制，等待 "立即沟通" 按钮出现
//                         const continueButton = await waitForElement('.job-detail-op .op-btn-chat', 10000); // 延长等待时间到10秒
//                         if (continueButton) {
//                             // continueButton.click();
//                             console.log('点击了 "立即沟通" 按钮.');
//                             //记录日志
//                              const data = {
//                               id:'',//顺序
//                               user_phone: '', // 替换为实际的电话号码
//                               user_job_expect:'',// 用户的介绍 人工智能部分
//                               user_inclination: JSON.stringify(jobKeywords) , // 替换为实际的关键字keyword
//                               job_title: jobTitle, // 替换为实际的岗位标题
//                               job_detail: jobDesc, // 替换为实际的工作详情
//                               job_match: 'true', // 替换为实际的匹配结果
//                               additional_greet: '在吗', // 替换为实际用户问候语的额外问候，现在先别管
//                               into_time: new Date().toISOString(), // 使用当前时间作为插入时间
//                               city: location ,// 替换为岗位的地址
//                               boss_name:jobNameTrim ,//公司名字
//                               is_delivery:'可以投递'
//                             };
//                             const result = window.bossHandleApi.dbInsert(data)
//                             console.log('result: ', result);
//                             console.log('执行了日志记录: ', data);
//                         }
//                     } else {
//                         console.log('未找到职位卡片来点击.');
//                     }
//                 } else {
//                     console.log('没有匹配上:', jobTitle, '-', location);
//                     //记录日志
//                      const data = {
//                        id:'',//顺序
//                       user_phone: '', // 替换为实际的电话号码
//                       user_job_expect:'',// 用户的介绍 人工智能部分
//                       user_inclination: JSON.stringify(jobKeywords) , // 替换为实际的关键字keyword
//                       job_title: jobTitle, // 替换为实际的岗位标题
//                       job_detail: jobDetail, // 替换为实际的工作详情
//                       job_match: 'false', // 替换为实际的匹配结果
//                       additional_greet: '', // 替换为实际用户问候语的额外问候，现在先别管
//                       into_time: new Date().toISOString(), // 使用当前时间作为插入时间
//                       city: location ,// 替换为岗位的地址
//                       boss_name:jobNameTrim ,//公司名字
//                       is_delivery:'可以投递'
//                     };
//                     console.log('执行了日志记录: ', data);
//                     const result = window.bossHandleApi.dbInsert(data)
//                     console.log('result: ', result);
//                 }
//
//                 // 延迟10秒
//                 await delay(10000);
//             }
//         };
//
//         const scrollAndCheckNewItems = async (maxWaitTime = 15000, interval = 500) => {
//             const startTime = Date.now();
//             let previousItemCount = document.querySelectorAll('.rec-job-list .company-location').length;
//
//             while (Date.now() - startTime < maxWaitTime) {
//                 window.scrollTo(0, document.body.scrollHeight);
//                 console.log('模拟滚动到页面底部.');
//
//                 await delay(interval);
//
//                 const newItemCount = document.querySelectorAll('.rec-job-list .company-location').length;
//                 if (newItemCount > previousItemCount) {
//                     console.log('发现新的职位项，继续处理.');
//                     return true; // 新内容加载完成
//                 }
//
//                 console.log('没有新职位项加载，继续等待.');
//             }
//             console.log('超时未加载到新的职位项.');
//             return false; // 超时未加载新内容
//         };
//
//         // 轮询处理直到没有新项目加载
//         while (true) {
//             await processJobItems();
//             const newItemsLoaded = await scrollAndCheckNewItems();
//             if (!newItemsLoaded) {
//                 console.log('没有新的职位项加载，结束脚本.');
//                 break;
//             }
//         }
//     })();
// `);
//     } catch (error) {
//         console.error('处理提交简历时出错:', error);
//     }
//
// }


// 投递脚本 -- 新的
async function selectCardCondition(mainWindow, jsonPositionCondition) {
    console.log('======================================================');
    console.log('======= 提交简历 =======');
    console.log('======= 进入提交 =======');

    const modifiedJsonPositionCondition = JSON.parse(jsonPositionCondition);
    const jobKeywords = modifiedJsonPositionCondition.jobKeywords.length > 0
        ? modifiedJsonPositionCondition.jobKeywords
        : [modifiedJsonPositionCondition.likeJob];
    console.log('职位关键词', jobKeywords);

    try {
        await mainWindow.webContents.executeJavaScript(`
    (async () => {
        console.log('=== 执行注入脚本 ===');
        const modifiedJsonPositionCondition = ${JSON.stringify(modifiedJsonPositionCondition)};
        const jobKeywords = ${JSON.stringify(jobKeywords)};

        const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

        const waitForElement = async (selector, timeout = 10000) => {
            const startTime = Date.now();
            while (Date.now() - startTime < timeout) {
                const element = document.querySelector(selector);
                if (element) {
                    return element;
                }
                await delay(100);
            }
            console.log('等待超时，未找到元素:', selector);
            return null;
        };

        const checkPauseOrStop = async () => {
            let pauseScript = await window.bossHandleApi.pauseScript(null);
            console.log('打印检查脚本进程值', pauseScript);
            while (pauseScript == true) {
                console.log('脚本已暂停...');
                pauseScript = await window.bossHandleApi.pauseScript(null);
                console.log('打印检查脚本进程值', pauseScript);
                await delay(1000);
            }
            if (localStorage.getItem('stopScript') == 'true') {
                console.log('脚本已停止 关闭投递窗口.');
                throw new Error('Script stopped');
            }
        };

        const processJobItems = async () => {
            const jobListItems = document.querySelectorAll('.rec-job-list .company-location');
            console.log('找到的职位列表项:', jobListItems.length);

            if (jobListItems.length === 0) {
                return false;
            }

            const cities = modifiedJsonPositionCondition.city.split('/');

            for (const [index, item] of jobListItems.entries()) {
                await checkPauseOrStop();

                const location = item.innerText.trim();
                console.log('职位地点:', location);

                const cityMatch = cities.some(city => location.includes(city));
                console.log('城市列表:', cities);
                console.log('城市匹配结果:', cityMatch);

                const jobButton = item.closest('.job-card-box').querySelector('.job-name');
                const jobTitle = jobButton ? jobButton.innerText.trim() : '';
                console.log('职位标题:', jobTitle);

                const jobName = item.closest('.job-card-box').querySelector('.boss-name');
                const jobNameTrim = jobName ? jobName.innerText.trim() : '';
                console.log('公司名字:', jobNameTrim);

                let jobDesc = '';

                const jobCardBox = item.closest('.job-card-box');
                if (jobCardBox) {
                    jobCardBox.click();
                    console.log('点击了职位卡片.');
                    await delay(5000); // 每处理完一个职位后等待10秒
                    console.log('============职位描述匹配开始=============');
                    const jobDescElement = await waitForElement('.job-detail-body .desc');
                    if (jobDescElement) {
                        // 获取所有子节点
                        const childNodes = jobDescElement.childNodes;

                        // 遍历子节点，筛选出文本节点并拼接内容
                        childNodes.forEach(node => {
                            if (node.nodeType === Node.TEXT_NODE) { // 筛选文本节点
                                jobDesc += node.textContent.trim(); // 拼接文本内容，去除两端空白
                            }
                        });

                        console.log('职位描述:', jobDesc);
                    } else {
                        console.log('未找到符合条件的职位描述元素');
                    }
                    console.log('执行数据入库');
                    const data = {
                        id: '',
                        user_phone: '',
                        user_job_expect: '',
                        user_inclination: JSON.stringify(jobKeywords),
                        job_title: jobTitle,
                        job_detail: jobDesc,
                        job_match: cityMatch ? 'true' : 'false', // 只检查城市匹配，关键词匹配通过后续代码处理
                        additional_greet: '',
                        into_time: new Date().toISOString(),
                        city: location,
                        boss_name: jobNameTrim,
                        is_delivery: '可以投递'
                    };
                    console.log('执行了日志记录: ', data);
                    const result = window.bossHandleApi.dbInsert(data);
                    console.log('result: ', result);
                } else {
                    console.log('未找到职位卡片来点击.');
                }

                console.log('本次执行的结果', '------公司名字：', jobNameTrim, '---------职位标题', '--------城市列表', cities, '---------城市匹配结果', cityMatch, '------职位描述', jobDesc);
                await delay(10000);
            }

            return true;
        };

        const scrollAndCheckNewItems = async (maxWaitTime = 15000, interval = 500) => {
            const startTime = Date.now();
            let previousItemCount = document.querySelectorAll('.rec-job-list .company-location').length;

            while (Date.now() - startTime < maxWaitTime) {
                await checkPauseOrStop();

                window.scrollTo(0, document.body.scrollHeight);
                console.log('模拟滚动到页面底部.');

                await delay(interval);

                const newItemCount = document.querySelectorAll('.rec-job-list .company-location').length;
                if (newItemCount > previousItemCount) {
                    console.log('发现新的职位项，继续处理.');
                    return true;
                }

                console.log('没有新职位项加载，继续等待.');
            }
            console.log('超时未加载到新的职位项.');
            return false;
        };

        while (true) {
            await checkPauseOrStop();
            const processed = await processJobItems();
            if (!processed) {
                console.log('所有职位项已处理，结束脚本.');
                break;
            }
            const newItemsLoaded = await scrollAndCheckNewItems();
            if (!newItemsLoaded) {
                console.log('没有新的职位项加载，结束脚本.');
                break;
            }
        }
    })();
`);
    } catch (error) {
        console.error('处理提交简历时出错:', error);
    }
}



// ai投递接口
async function aiSelectCardCondition(mainWindow, jsonPositionCondition) {
    console.log('ai筛选脚本');
    console.log('======= 提交简历 =======');
    console.log('======= 进入提交 =======');

    const modifiedJsonPositionCondition = JSON.parse(jsonPositionCondition);
    const jobKeywords = modifiedJsonPositionCondition.jobKeywords.length > 0
        ? modifiedJsonPositionCondition.jobKeywords
        : [modifiedJsonPositionCondition.likeJob];
    console.log('职位关键词', jobKeywords);

    try {
        await mainWindow.webContents.executeJavaScript(`
    (async () => {
        console.log('=== 执行注入脚本 ===');
        const modifiedJsonPositionCondition = ${JSON.stringify(modifiedJsonPositionCondition)};
        const jobKeywords = ${JSON.stringify(jobKeywords)};

        const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

        const waitForElement = async (selector, timeout = 10000) => {
            const startTime = Date.now();
            while (Date.now() - startTime < timeout) {
                const element = document.querySelector(selector);
                if (element) {
                    return element;
                }
                await delay(100);
            }
            console.log('等待超时，未找到元素:', selector);
            return null;
        };

        const checkPauseOrStop = async () => {
            let pauseScript = await window.bossHandleApi.pauseScript(null);
            console.log('打印检查脚本进程值', pauseScript);
            while (pauseScript == true) {
                console.log('脚本已暂停...');
                pauseScript = await window.bossHandleApi.pauseScript(null);
                console.log('打印检查脚本进程值', pauseScript);
                await delay(1000);
            }
            if (localStorage.getItem('stopScript') == 'true') {
                console.log('脚本已停止 关闭投递窗口.');
                throw new Error('Script stopped');
            }
        };

        const processJobItems = async () => {
            const jobListItems = document.querySelectorAll('.rec-job-list .company-location');
            console.log('找到的职位列表项:', jobListItems.length);

            const cities = modifiedJsonPositionCondition.city.split('/');

            for (const [index, item] of jobListItems.entries()) {
                await checkPauseOrStop();

                const location = item.innerText.trim();
                console.log('职位地点:', location);

                const cityMatch = cities.some(city => location.includes(city));
                console.log('城市列表:', cities);
                console.log('城市匹配结果:', cityMatch);

                const jobButton = item.closest('.job-card-box').querySelector('.job-name');
                const jobTitle = jobButton ? jobButton.innerText.trim() : '';
                console.log('职位标题:', jobTitle);

                const jobName = item.closest('.job-card-box').querySelector('.boss-name');
                const jobNameTrim = jobName ? jobName.innerText.trim() : '';
                console.log('公司名字:', jobNameTrim);

                let jobDesc = '';

                const jobCardBox = item.closest('.job-card-box');
                if (jobCardBox) {
                    jobCardBox.click();
                    console.log('点击了职位卡片.');
                    await delay(5000); // 每处理完一个职位后等待5秒
                    console.log('============职位描述匹配开始=============');
                    const jobDescElement = await waitForElement('.job-detail-body .desc');
                    if (jobDescElement) {
                        // 获取所有子节点
                        const childNodes = jobDescElement.childNodes;
                    
                        // 遍历子节点，筛选出文本节点并拼接内容
                        childNodes.forEach(node => {
                            if (node.nodeType === Node.TEXT_NODE) { // 筛选文本节点
                                jobDesc += node.textContent.trim(); // 拼接文本内容，去除两端空白
                            }
                        });
                    
                        console.log('职位描述:', jobDesc);
                    } else {
                        console.log('未找到符合条件的职位描述元素');
                    }

                    // ai预留接口 与服务端交互接口
                    const userDescribe = modifiedJsonPositionCondition.userJobExpect;
                    const jobRequirement = jobDesc;

                    try {
                        const fetchWithTimeout = (url, options, timeout = 60000) => {
                            return Promise.race([
                                fetch(url, options),
                                new Promise((_, reject) => setTimeout(() => reject(new Error('请求超时')), timeout))
                            ]);
                        };

                        const response = await fetchWithTimeout('http://sleepyhealing.online:11747/ai/aliTyqw', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                usrDescribe: userDescribe,
                                jobRequirement: jobRequirement
                            })
                        });

                        const result = await response.json();
                        console.log('AI匹配结果: ', result);
                        const data = {
                            id: '',
                            user_phone: '',
                            user_job_expect: userDescribe,
                            user_inclination: JSON.stringify(jobKeywords),
                            job_title: jobTitle,
                            job_detail: jobDesc,
                            job_match: result&&cityMatch ? 'true' : 'false',
                            additional_greet: '',
                            into_time: new Date().toISOString(),
                            city: location,
                            boss_name: jobNameTrim,
                            is_delivery: '可以投递'
                        };
                        console.log('执行了日志记录: ', data);
                        const dbResult = window.bossHandleApi.dbInsert(data);
                        console.log('DB Insert result: ', dbResult);
                    } catch (error) {
                        console.error('调用AI匹配接口出错: ', error);
                    }
                } else {
                    console.log('未找到职位卡片来点击.');
                }

                await delay(10000);
            }
        };

        const scrollAndCheckNewItems = async (maxWaitTime = 150000, interval = 500) => {
            const startTime = Date.now();
            let previousItemCount = document.querySelectorAll('.rec-job-list .company-location').length;

            while (Date.now() - startTime < maxWaitTime) {
                await checkPauseOrStop();

                window.scrollTo(0, document.body.scrollHeight);
                console.log('模拟滚动到页面底部.');

                await delay(interval);

                const newItemCount = document.querySelectorAll('.rec-job-list .company-location').length;
                if (newItemCount > previousItemCount) {
                    console.log('发现新的职位项，继续处理.');
                    return true;
                }

                console.log('没有新职位项加载，继续等待.');
            }
            console.log('超时未加载到新的职位项.');
            return false;
        };

        while (true) {
            await checkPauseOrStop();
            await processJobItems();
            const newItemsLoaded = await scrollAndCheckNewItems();
            if (!newItemsLoaded) {
                console.log('没有新的职位项加载，结束脚本.');
                break;
            }
        }
    })();
`);
    } catch (error) {
        console.error('处理提交简历时出错:', error);
    }
}



// 打招呼功能的实现
ipcMain.handle('greet-title',(event,jsonPositionCondition)=>{
    greetTitle(deliveryWindow,jsonPositionCondition)
})

async function greetTitle(mainWindow, jsonPositionCondition) {
    console.log('======================================================');
    console.log('======= 打招呼 =======');
    console.log('======= 进入打招呼 =======');

    const modifiedJsonPositionCondition = JSON.parse(jsonPositionCondition);
    const targetJobTitle = modifiedJsonPositionCondition.job_title;

    console.log('目标职位标题', targetJobTitle);

    try {
        // 先暂停海投脚本
        await mainWindow.webContents.executeJavaScript(`window.bossHandleApi.pauseScript(true);`);

        // 执行打招呼操作
        await mainWindow.webContents.executeJavaScript(`
            (async () => {
                console.log('=== 执行打招呼操作 ===');

                const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

                const waitForElement = async (selector, timeout = 10000) => {
                    const startTime = Date.now();
                    while (Date.now() - startTime < timeout) {
                        const element = document.querySelector(selector);
                        if (element) {
                            return element;
                        }
                        await delay(100);
                    }
                    console.log('等待超时，未找到元素:', selector);
                    return null;
                };

                const jobTitle = ${JSON.stringify(targetJobTitle)};
                console.log('目标职位标题:', jobTitle);

                const jobItems = document.querySelectorAll('.rec-job-list .job-card-box');
                console.log('找到的职位卡片数量:', jobItems.length);

                for (const jobItem of jobItems) {
                    const jobNameElement = jobItem.querySelector('.job-name');
                    const jobName = jobNameElement ? jobNameElement.innerText.trim() : '';

                    if (jobName === jobTitle) {
                        console.log('找到匹配的职位:', jobName);
                        jobItem.click();
                        console.log('点击了职位卡片:', jobName);

                        // 等待并点击立即沟通按钮
                        const continueButton = await waitForElement('.job-detail-op .op-btn-chat', 10000);
                        if (continueButton) {
                            continueButton.click();
                            console.log('点击了 "立即沟通" 按钮.');

                            // 等待2秒后尝试点击关闭按钮
                            console.log('等待2秒后尝试点击关闭按钮。');
                            await delay(2000); // 等待2秒钟
                            const closeButton = await waitForElement('.close', 5000);
                            if (closeButton) {
                                closeButton.click();
                                console.log('点击了关闭按钮。');

                                // 等待2秒后尝试点击取消按钮
                                console.log('等待2秒后尝试点击取消按钮。');
                                await delay(2000); // 等待2秒钟
                                const cancelButton = await waitForElement('.cancel-btn', 5000);
                                if (cancelButton) {
                                    cancelButton.click();
                                    console.log('点击了取消按钮。');
                                } else {
                                    console.log('未找到取消按钮。');
                                }
                            } else {
                                console.log('未找到关闭按钮。');
                            }
                        } else {
                            console.log('未找到 "立即沟通" 按钮。');
                        }
                        break;
                    } else {
                        console.log('职位不匹配:', jobName);
                    }
                }

                // 恢复海投脚本
                window.bossHandleApi.pauseScript(false);
            })();
        `);
    } catch (error) {
        console.error('执行打招呼操作时出错:', error);
    }
}


//获取到投递的状态
ipcMain.handle('get-delivery-status',()=>{
    return deliveryWindow == null
})